package graph.group.zhangtao.guider.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import graph.group.zhangtao.guider.NavigationActivity;
import graph.group.zhangtao.guider.R;
import graph.group.zhangtao.guider.getter.DownloadAndUnzip;
import graph.group.zhangtao.guider.getter.ImageGetterFactory;
import graph.group.zhangtao.guider.getter.TextGetterFactory;
import graph.group.zhangtao.guider.model.ViewKey;
import graph.group.zhangtao.guider.utils.GetLocalFiles;
import graph.group.zhangtao.guider.utils.MySettingsAndTools;

/**
 * Created by guwei on 16-7-28.
 */
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
    private LayoutInflater inflater;
    private Context mContext;
    private String mDatas;
    private List<ViewKey> wrong;
    private List<ViewKey> items;
    private boolean status = false;
    private RecyclerView recyclerView;

    //创建构造参数
    public MyAdapter(Context context, RecyclerView recyclerView) {
        this.mContext = context;
        this.recyclerView = recyclerView;
        inflater = LayoutInflater.from(context);
        wrong = new LinkedList<>();
        ViewKey viewKey = new ViewKey("获取失败！请检查网络,点击重试。");
        wrong.add(viewKey);
        bind();
    }

    private void bind() {
        this.mDatas = TextGetterFactory.textGet(mContext, MySettingsAndTools.getIndexPath(), false);

        if (mDatas.equals(MySettingsAndTools.getWRONG())) {
            //错误
            items = wrong;
            status = false;
//            updateList(items);
        } else {
            //刷新列表
            try {
                Set<ViewKey> viewKeySet = new HashSet<>();
                for (ViewKey viewKey : GetLocalFiles.viewKeys) {
                    viewKeySet.add(viewKey);
                }
                JSONArray jsonArray = new JSONArray(mDatas);
                for (int i = 0; i < jsonArray.length(); i++) {
                    String temp = jsonArray.getString(i);
                    ViewKey viewKey = new ViewKey(temp);
                    viewKeySet.add(viewKey);
                }
                items = new ArrayList<>();
                for (ViewKey viewKey : viewKeySet) {
                    items.add(viewKey);
                }
                status = true;

            } catch (JSONException e) {
                e.printStackTrace();
                status = false;

                Log.d("tao", "wrong");
            }
        }
    }
//    private void updateList(List<String> lists) {
//        final Object[] strs = lists.toArray();
//        listView.setAdapter(new ArrayAdapter<>(context,
//                android.R.layout.simple_list_item_1, strs));
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                new MainIndexJsonGetter(listView,path,context).execute();
//            }
//        });
//    }

    //创建ViewHolder
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.recycle_item, parent, false);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }

    //绑定ViewHolder
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        //为textview 赋值
        final ViewKey viewKey = items.get(position);
        //设置图片
        String bgurl = MySettingsAndTools.getNOPICTURE();
        if (!status) {
            holder.tv.setText(viewKey.getName());
            ImageGetterFactory.setImageView(holder.iv, MySettingsAndTools.getNOPICTURE(), false);
        } else {
            if (viewKey.isLocal()) {
                try {
                    String path = viewKey.getName() + "/index.json";
                    String index = TextGetterFactory.textGet(mContext,
                            GetLocalFiles.getFullDirPath() + path, true);
                    JSONObject jsonObject = new JSONObject(index);
                    JSONArray nodes = jsonObject.getJSONArray("nodes");
                    JSONObject node1 = (JSONObject) nodes.get(0);
                    String id = node1.getString("id");
                    String child = TextGetterFactory.textGet(mContext,
                            GetLocalFiles.getFullDirPath() + viewKey.getName() + "/" + id + "/index.json", true);
                    JSONObject content = new JSONObject(child);
                    JSONArray contents = content.getJSONObject("text").getJSONArray("contents");
                    JSONObject jsonObject1 = (JSONObject) contents.get(0);
                    String type = jsonObject1.getString("type");
                    String url = GetLocalFiles.getFullDirPath() + viewKey.getName() + "/" + id;
                    if (type.equals("img")) {
                        String uid = jsonObject1.getString("url");
                        url = url + "/" + uid;
                        bgurl = url;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    bgurl = MySettingsAndTools.getNOPICTURE();

                }
                holder.tv.setText(viewKey.getName());
                ImageGetterFactory.setImageView(holder.iv, bgurl, true);
            } else {
                try {
                    String mText = URLEncoder.encode(viewKey.getName(), "UTF-8");
                    String path = MySettingsAndTools.getSourcePath() + mText + "/index.json";
                    String index = TextGetterFactory.textGet(mContext, path, false);
                    JSONObject jsonObject = new JSONObject(index);
                    JSONArray nodes = jsonObject.getJSONArray("nodes");
                    JSONObject node1 = (JSONObject) nodes.get(0);
                    String id = node1.getString("id");
                    String child = TextGetterFactory.textGet(mContext,
                            MySettingsAndTools.getSourcePath() + mText + "/" + id + "/index.json", false);
                    JSONObject content = new JSONObject(child);
                    JSONArray contents = content.getJSONObject("text").getJSONArray("contents");
                    JSONObject jsonObject1 = (JSONObject) contents.get(0);
                    String type = jsonObject1.getString("type");
                    String url = MySettingsAndTools.getSourcePath() + mText + "/" + id;
                    if (type.equals("img")) {
                        String uid = jsonObject1.getString("url");
                        url = url + "/" + uid;
                        bgurl = url;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    bgurl = MySettingsAndTools.getNOPICTURE();

                }
                holder.tv.setText(viewKey.getName());
                ImageGetterFactory.setImageView(holder.iv, bgurl, false);
            }

        }


        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!status) {
                    Toast.makeText(mContext, viewKey.getName(), Toast.LENGTH_SHORT).show();
                    bind();
                    notifyDataSetChanged();
                } else {
                    Intent intent = new Intent(mContext, NavigationActivity.class);
                    intent.putExtra("id", viewKey.getName());
                    intent.putExtra("isLocal", viewKey.isLocal());
                    mContext.startActivity(intent);
                }
            }
        });
        holder.itemView.setLongClickable(true);
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (status) {
                    Toast.makeText(mContext, "开始下载！", Toast.LENGTH_SHORT).show();
                    new DownloadAndUnzip(mContext, viewKey.getName()).execute();
                    return true;
                }
                return false;
            }
        });
    }


    @Override
    public int getItemCount() {
        //Log.i("TAG", "mDatas "+mDatas);

        return items.size();

    }


//    //新增item
//    public void addData(int pos) {
//        items.add("新增");
//        notifyItemInserted(pos);
//    }
//
//    //移除item
//    public void deleateData(int pos) {
//        items.remove(pos);
//        notifyItemRemoved(pos);
//    }
}

class MyViewHolder extends RecyclerView.ViewHolder {

    TextView tv;
    ImageView iv;

    public MyViewHolder(View itemView) {
        super(itemView);
        tv = (TextView) itemView.findViewById(R.id.recycle_tv);
        iv = (ImageView) itemView.findViewById(R.id.recycle_iv);
    }
}